package com.jjkj.environmental.environmental.utils

import com.jjkj.environmental.environmental.utils.pull.PullConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit

object Retrofit2Utils {
    @Volatile
    private var sOkHttpClient: OkHttpClient? = null
    @Volatile
    private var sRetrofit: Retrofit? = null

    private val okHttpClient: OkHttpClient?
        get() {
            if (sOkHttpClient == null) {
                synchronized(Retrofit2Utils::class.java) {
                    val builder = OkHttpClient.Builder()
                    val logger = HttpLoggingInterceptor { MyLog.i("HTTP_LOG", it) }
                    logger.level = HttpLoggingInterceptor.Level.BODY
                    sOkHttpClient = builder
                            .writeTimeout(30, TimeUnit.SECONDS)
                            .readTimeout(30, TimeUnit.SECONDS)
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .addInterceptor(logger)
                            .build()
                }
            }
            return sOkHttpClient
        }

    private fun getRetrofit(url: String): Retrofit? {
        if (sRetrofit == null) {
            synchronized(Retrofit2Utils::class.java) {
                sRetrofit = Retrofit.Builder()
                        .client(okHttpClient!!)
                        .addConverterFactory(PullConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .baseUrl(url)
                        .build()
            }
        } else if (sRetrofit!!.baseUrl().toString() != url) {
            sRetrofit = null
            getRetrofit(url)
        }
        return sRetrofit

    }


    fun <S> getServiceApi(serviceClass: Class<S>, url: String): S {
        return getRetrofit(url)!!.create(serviceClass)
    }
}